package com.yepit.translate.util.translate.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yepit.translate.dto.TransRespose;
import com.yepit.translate.util.http.HttpGet;
import com.yepit.translate.util.md5.MD5Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class BaiduTransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    @Value("${baidu.translate.appId}")
    private String appid;

    @Value("${baidu.translate.secretKey}")
    private String securityKey;

    public BaiduTransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }

    public BaiduTransApi() {
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }

    public TransRespose getSingleTransResp(String query, String from, String to) {
        TransRespose resp = null;
        String result = this.getTransResult(query, from, to);
        if (StringUtils.isNotBlank(result)) {
            resp = new TransRespose();
            JSONObject jsonObject = JSON.parseObject(result);
            JSONArray transResultArray = jsonObject.getJSONArray("trans_result");
            resp.setFrom(from);
            resp.setTo(to);
            if (transResultArray == null) {
                return null;
            }
            if (transResultArray.size() > 0) {
                TransRespose.TranslateResult translateResult = new TransRespose().new TranslateResult();
                StringBuffer content = new StringBuffer();
                for (int i = 0; i < transResultArray.size(); i++) {
                    JSONObject transResultObj = transResultArray.getJSONObject(i);
                    content.append(transResultObj.getString("dst") + "\n");
                }
                translateResult.setDst(content.toString());
                translateResult.setSrc(query);
                resp.setTransResult(translateResult);
            }
            return resp;
        }
        return null;
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5Utils.md5(src));

        return params;
    }

}
